import logging
import os
import datetime


class CustomFormatter(logging.Formatter):
    green = "\x1b[32;32m"
    blue = "\x1b[38;5;39m"
    yellow = "\x1b[33;21m"
    red = "\x1b[31;21m"
    bold_red = "\x1b[31;1m"
    reset = "\x1b[0m"
    fmt = "%(asctime)s - [%(levelname)s | %(name)s | %(filename)s:%(lineno)s] > %(message)s"

    def __init__(self):
        super().__init__()
        self.FORMATS = {
            logging.DEBUG: self.green + self.fmt + self.reset,
            logging.INFO: self.blue + self.fmt + self.reset,
            logging.WARNING: self.yellow + self.fmt + self.reset,
            logging.ERROR: self.red + self.fmt + self.reset,
            logging.CRITICAL: self.bold_red + self.fmt + self.reset,
        }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)


class MyLogger:
    _logger = None

    def __new__(cls, *args, **kwargs):  # type: ignore
        if cls._logger is None:
            cls._logger = super().__new__(cls, *args, **kwargs)  # type: ignore
            cls._logger = logging.getLogger("MAIN")
            cls._logger.setLevel(logging.DEBUG)

            now = datetime.datetime.now()
            dirname = "./log"

            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            fileHandler = logging.FileHandler(
                dirname + "/log_" + now.strftime("%Y-%m-%d") + ".log",
                encoding="utf-8",
            )

            streamHandler = logging.StreamHandler()

            fileHandler.setFormatter(CustomFormatter())
            streamHandler.setFormatter(CustomFormatter())

            cls._logger.addHandler(fileHandler)
            cls._logger.addHandler(streamHandler)

        return cls._logger
